package com.chen.project.white_jotter.config;

import com.chen.project.white_jotter.mapper.AdminUserRoleMapper;
import com.chen.project.white_jotter.mapper.UserMapper;
import com.chen.project.white_jotter.pojo.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service("userDetailsService")
public class SecurityUserDetailsService implements UserDetailsService {

    @Resource
    UserMapper userMapper;
    @Resource
    private AdminUserRoleMapper adminUserRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 通过用户名查询用户
        User user = userMapper.selectUserByUsername(username);
        if (user == null) {
            return null;
        }
        // 通过用户id，查询用户角色
        Integer roleId = adminUserRoleMapper.selectRoleIdByUserId(user.getId());
        String roles = "";
        if (roleId == 1) {
            roles = "admin";

        } else if (roleId == 2) {
            roles = "normal";
        }
        return org.springframework.security.core.userdetails.User
                .withUsername(user.getUsername())
                .password(user.getPassword())
                .roles(roles)
                .build();
    }
}

